package database

import (
	_ "github.com/go-sql-driver/mysql"
	"go-sec-code/model"
	"log"
	"strings"
	"xorm.io/xorm"
)

type XormUser struct {
}

func NewXormUser() *XormUser {
	return &XormUser{}
}

func (*XormUser) GetEngine() *xorm.Engine {
	dsn := "root:111111@tcp(127.0.0.1:3306)/go_sec_code?charset=utf8mb4&parseTime=True&loc=Local"
	engine, err := xorm.NewEngine("mysql", dsn)
	if err != nil {
		log.Printf("Failed to connect to database: %v", err)
		return nil
	}
	engine.ShowSQL(true)
	return engine
}

func (*XormUser) SelectUsersByName(engine *xorm.Engine, name string, field string) []model.User {
	var users []model.User
	//engine.Where("name = '" + name + "'").Find(&users)
	//engine.Where("name = ?", name).Find(&users)

	//engine.Where("name like '%" + name + "%'").Find(&users)
	//engine.Where("name like ?", "%" + name + "%").Find(&users)

	engine.Where("name = ?", name).Desc(field).Find(&users)

	//engine.Where("name = ?", name).GroupBy(field).Find(&users)
	return users;
}

func (*XormUser) SelectUsersLimit(engine *xorm.Engine) []map[string][]byte {
	res, _ := engine.SQL("select * from user limit ? offset ?", 2, 0).Query()
	return res;
}

func (*XormUser) SelectUsersIn(engine *xorm.Engine, ids []int) []model.User {
	var users []model.User

	// 初始化 condition 和 params
	condition := "id in ("
	params := make([]interface{}, 0, len(ids))

	// 构建 condition 和 params
	placeholders := make([]string, 0, len(ids))
	for _, id := range ids {
		placeholders = append(placeholders, "?")
		params = append(params, id)
	}

	// 使用 strings.Join 拼接 placeholders
	condition += strings.Join(placeholders, ", ") + ")"

	engine.Where(condition, params...).Find(&users)
	return users
}
